﻿using Growatt.ShinebusServiceUploadPack.Controllers;
using System.Net.Http;

namespace Growatt.ShinebusServiceUploadPack.Service.OSS
{
    public class GetAuthorizationToken
    {
        private string _authToken;
        private DateTime? _tokenExpiryTime;
        private readonly IHttpClientFactory _httpClientFactory;
        public GetAuthorizationToken(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        // 获取或刷新token的方法
        public async Task<string> GetAuthorizationTokenAsync(ILogger<UpdatePackController> logger, String Server)
        {
            // 如果token为空或已经过期，则获取新的token
            if (_authToken == null || _tokenExpiryTime < DateTime.Now)
            {
                using (HttpClient client = _httpClientFactory.CreateClient("OSS"))
                {
                    var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("op", "getUploadFileCloudAuthToken") });

                    HttpResponseMessage response = await client.PostAsync($"http://{Server}/pubData.do", content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        _authToken = responseBody;
                        _tokenExpiryTime = DateTime.Now.AddHours(1); // 设置token过期时间为1小时后
                        logger.LogInformation("获取授权token成功: " + _authToken);
                    }
                    else
                    {
                        logger.LogInformation("获取授权token失败: " + response.StatusCode);
                        _authToken = null; // 清空无效token
                    }
                }
            }

            return _authToken;
        }

        // 检查token是否有效的方法
        public bool IsTokenValid()
        {
            return _authToken != null && _tokenExpiryTime > DateTime.Now;
        }
    }
}
